from django.http import HttpResponse,HttpResponseRedirect
from django.template.loader import get_template
from django.shortcuts import render,render_to_response
from django import forms
from django.contrib.auth.models import User
from django.views.decorators.csrf import csrf_exempt
from django.contrib.sessions.models import Session
from captcha.fields import CaptchaField
from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url
import django.contrib.auth as auth
import json

class UserForm(forms.Form):
    style = 'form-control'
    username = forms.CharField(
        widget=forms.TextInput(attrs={'class': style,'name': 'username','placeholder':'账号'}),
        label=u"账号",
        max_length=64,
        required=True,
        error_messages={
            'required':u'账号不能为空',
            'max_length':u'账号不能超过64位',
        }
    )
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': style, 'name': 'password','placeholder':'密码'}),
        label=u"密码",
        max_length=255,
        required=True,
        error_messages={
            'required': u'密码不能为空',
            'max_length': u'密码不能超过64位'
        }
    )
    email    = forms.EmailField(
        widget=forms.EmailInput(attrs={'class': style, 'name': 'email','placeholder':'邮箱'}),
        label=u"邮箱",
        required=True,
        error_messages={
            'required': u'邮箱不能为空',
        }
    )
    # 验证码
    captcha = CaptchaField(
        error_messages={"invalid": u"验证码错误"}
    )


class LoginForm(forms.Form):
    style = 'form-control input-lg'
    username = forms.CharField(
        widget=forms.TextInput(attrs={'class': style, 'name': 'username', 'placeholder': '账号'}),
        label=u"账号",
        max_length=64,
        required=True,
        error_messages={
            'required': u'账号不能为空',
            'max_length': u'账号不能超过64位',
        }
    )
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': style, 'name': 'password', 'placeholder': '密码'}),
        label=u"密码",
        max_length=255,
        required=True,
        error_messages={
            'required': u'密码不能为空',
            'max_length': u'密码不能超过64位'
        }
    )


@csrf_exempt
def login(request):
    if request.method == 'POST':
        loginForm = LoginForm(request.POST)
        if loginForm.is_valid():
            username = loginForm.cleaned_data['username']
            password = loginForm.cleaned_data['password']
            user = auth.authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    auth.login(request, user)
                    return HttpResponseRedirect('/backend/index/')
                else:
                    return render(request, "backend/login/index.html",
                                  {"loginForm": loginForm, 'password_error': '账号被拉黑'})
            else:
                return render(request, "backend/login/index.html", {"loginForm": loginForm, 'username_error': '账号或密码错误'})
        else:
            return HttpResponse('GET')
            return render(request, "backend/login/index.html", {"error": loginForm.errors, 'loginForm': loginForm})

    else:
        loginForm = LoginForm()
    return render_to_response('backend/login/index.html', {'loginForm': loginForm})


@csrf_exempt
def reg(request):
    if request.method == "POST":
        userform = UserForm(request.POST)
        if userform.is_valid():
            username = userform.cleaned_data['username']
            password = userform.cleaned_data['password']
            email = userform.cleaned_data['email']
            user = auth.authenticate(username=username, password=password)
            if user:
                hashkey = CaptchaStore.generate_key()
                imgage_url = captcha_image_url(hashkey)
                return render(request, "backend/login/reg.html", {"userform": userform, 'username_error': '账号已注册','hashkey':hashkey,'imgage_url':imgage_url})
            res = User.objects.create_user(
                username=username,
                password=password,
                email=email,
            )
            #res.save()
            request.session['username'] = username
            auth.login(request, user)
            return HttpResponseRedirect('/backend/index')
        else:
            hashkey = CaptchaStore.generate_key()
            imgage_url = captcha_image_url(hashkey)
            return render(request, "backend/login/reg.html", {"error": userform.errors, 'userform':userform,'hashkey':hashkey,'imgage_url':imgage_url})
    else:
        userform = UserForm()
    hashkey = CaptchaStore.generate_key()
    imgage_url = captcha_image_url(hashkey)
    return render_to_response('backend/login/reg.html', {'userform':userform,'hashkey':hashkey,'imgage_url':imgage_url})

def logout(request):
    #清理cookie里保存username
    auth.logout(request)
    return HttpResponseRedirect('/backend/login')


@csrf_exempt
def test(request):
    if request.method == 'POST':
        loginForm = LoginForm(request.POST)
        if loginForm.is_valid():
            username = loginForm.cleaned_data['username']
            password = loginForm.cleaned_data['password']
            user = auth.authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    auth.login(request, user)
                    session_key = request.session.session_key
                    request.session['test'] = '我就是测试啊'
                    res = {'status':'success', 'session_id':session_key}
                    response = HttpResponse(json.dumps(res), content_type="application/json")
                    response["Access-Control-Allow-Origin"] = "*"
                    response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
                    response["Access-Control-Max-Age"] = "1000"
                    response["Access-Control-Allow-Headers"] = "*"
                    return  response
                else:
                    res = {'status': '拉黑'}
                    return HttpResponse(json.dumps(res), content_type="application/json")
            else:
                res = {'status': '账号或密码错误'}
                return HttpResponse(json.dumps(res), content_type="application/json")
        else:
            res = {'status': loginForm.errors}
            return HttpResponse(json.dumps(res), content_type="application/json")

def get_data(request):
    token = request.GET['token']
    sess = Session.objects.get(pk=token)
    res = sess.get_decoded()
    response = HttpResponse(json.dumps(res), content_type="application/json")
    response.set_cookie('sessionid',token)
    response["Access-Control-Allow-Origin"] = "*"
    response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
    response["Access-Control-Max-Age"] = "1000"
    response["Access-Control-Allow-Headers"] = "*"
    return response

# 刷新验证码
def refreshCaptcha(request):
    to_json_response = dict()
    to_json_response['status'] = 1
    to_json_response['new_cptch_key'] = CaptchaStore.generate_key()
    to_json_response['new_cptch_image'] = captcha_image_url(to_json_response['new_cptch_key'])
    return HttpResponse(json.dumps(to_json_response), content_type='application/json')